/*
 * Copyright 2020 www.mytijian.com All right reserved. This software is the
 * confidential and proprietary information of www.mytijian.com ("Confidential
 * Information"). You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license agreement you entered
 * into with www.mytijian.com.
 */
package com.mytijian.task.executor;

import com.mytijian.origin.components.threadpool.DefaultThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class GroupThreadFactory implements ThreadFactory {
    private static final Logger log = LoggerFactory.getLogger(DefaultThreadFactory.class);
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    protected GroupThreadFactory(String poolName) {
        SecurityManager s = System.getSecurityManager();
        this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        this.namePrefix = poolName + "-" + poolNumber.getAndIncrement() + "-thread-";
    }
    @Override
    public Thread newThread(Runnable r) {
        String threadName = this.namePrefix + this.threadNumber.getAndIncrement();
        log.info("thread " + threadName + "has been created");
        Thread t = new Thread(this.group, r, threadName, 0L);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }

        if (t.getPriority() != 5) {
            t.setPriority(5);
        }

        return t;
    }
}
